package com.ych.modules.base.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.ych.modules.base.dbEntity.TUserAccountChangeEntity;
import com.ych.modules.base.dbEntity.TUserAccountEntity;
import com.ych.modules.base.mapper.TUserAccountMapper;
import com.ych.modules.base.service.ITUserAccountChangeService;
import com.ych.modules.base.service.ITUserAccountService;
import com.ych.utils.UUID;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Created with IntelliJ IDEA.
 * Author: Usopp.tsui
 * Date: 2020/12/12
 * Time: 10:46
 * Description:
 */
@Service("ITUserAccountService")
public class TUserAccountServiceImpl extends ServiceImpl<TUserAccountMapper, TUserAccountEntity> implements ITUserAccountService {
    @Autowired
    private ITUserAccountChangeService itUserAccountChangeService;

    @Override
    public boolean updateByEntity(TUserAccountEntity entity) {
        boolean isok = false;
        try {
            if (StringUtils.isBlank(entity.getUserId())) {
                throw new RuntimeException("用户主键为空");
            }
            StringBuilder builder = new StringBuilder();
            //充值总金额
            if (null != entity.getCashAmount()) {
                builder.append("cash_amount = cash_amount + (");
                builder.append(entity.getCashAmount());
                builder.append(") ,");
            }
            //佣金
            if (null != entity.getBrokerageAmount()) {
                builder.append("brokerage_amount = brokerage_amount + (");
                builder.append(entity.getBrokerageAmount());
                builder.append(") ,");
            }
            //累计总获得佣金
            if (null != entity.getTotalBrokerageAmount()) {
                builder.append("total_brokerage_amount = total_brokerage_amount + (");
                builder.append(entity.getTotalBrokerageAmount());
                builder.append(") ,");
            }
            //当月月充值金额
            if (null != entity.getMonthAmount()) {
                builder.append("month_amount = month_amount + (");
                builder.append(entity.getMonthAmount());
                builder.append(") ,");
            }
            //金币数量
            if (null != entity.getGoldCoinAmount()) {
                builder.append("gold_coin_amount = gold_coin_amount +(");
                builder.append(entity.getGoldCoinAmount());
                builder.append(") ,");
            }
            //抽奖券
            if (null != entity.getRaffleTicket()) {
                builder.append("raffle_ticket = raffle_ticket +(");
                builder.append(entity.getRaffleTicket());
                builder.append(") ,");
            }
            //账户异常次数
            if (null != entity.getAbnormalNum()) {
                builder.append("abnormal_num = ");
                builder.append(entity.getAbnormalNum());
                builder.append(",");
            }
            //更新数据库时间
            builder.append("update_time = '");
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            builder.append(sdf.format(new Date()));
            builder.append("'");
            this.updateForSet(builder.toString(), new EntityWrapper<TUserAccountEntity>().eq("user_id", entity.getUserId()));
            isok = true;
        } catch (Exception e) {
            e.printStackTrace();
            isok = false;
        } finally {
            return isok;
        }
    }

    @Override
    @Transactional(isolation = Isolation.DEFAULT, propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public void alterGoldCoinAmount(String accountTrendType, String accountChangeBusinessType, String userId, String businessId, BigDecimal payAmount) {
        TUserAccountEntity accountEntity = this.selectById(userId);
        if (null == accountEntity) {
            throw new RuntimeException("用户不存在！");
        }
        TUserAccountChangeEntity changeEntity = new TUserAccountChangeEntity();
        changeEntity.setChangeId(UUID.randomUUID());
        changeEntity.setUserId(userId);
        changeEntity.setAccountTrend(accountTrendType);
        changeEntity.setBusinessId(businessId);
        changeEntity.setAccountChangeBusinessType(accountChangeBusinessType);
        //现金
        changeEntity.setCashAmount(BigDecimal.ZERO);
        changeEntity.setBeforeCashAmount(accountEntity.getCashAmount());
        changeEntity.setAfterCashAmount(accountEntity.getCashAmount());
        //金币
        changeEntity.setGoldCoinAmount(payAmount);
        changeEntity.setBeforeCashAmount(accountEntity.getGoldCoinAmount());
        switch (accountTrendType) {
            case "10000001"://收入
                changeEntity.setAfterGoldCoinAmount(accountEntity.getGoldCoinAmount().add(payAmount));
                break;
            case "10000002"://支出
                changeEntity.setAfterGoldCoinAmount(accountEntity.getGoldCoinAmount().subtract(payAmount));
                payAmount = payAmount.negate();//取反，用于下面账户减去处理
                break;
            default:
                throw new RuntimeException("未知资金流向类型");
        }
        //抽奖券
        changeEntity.setRaffleTicket(0);
        changeEntity.setBeforeRaffleTicket(accountEntity.getRaffleTicket());
        changeEntity.setAfterRaffleTicket(accountEntity.getRaffleTicket());
        changeEntity.setCreateTime(new Date());
        itUserAccountChangeService.insert(changeEntity);
        //账户金额减去
        TUserAccountEntity tempAccountEntity = new TUserAccountEntity();
        tempAccountEntity.setUserId(userId);
        tempAccountEntity.setGoldCoinAmount(payAmount);
        this.updateByEntity(tempAccountEntity);
    }

    @Override
    public void alterBrokerageAmount(String accountTrendType, String accountChangeBusinessType, String userId, String businessId, BigDecimal amount) {
        TUserAccountEntity accountEntity = this.selectById(userId);
        if (null == accountEntity) {
            throw new RuntimeException("用户不存在！");
        }
        TUserAccountChangeEntity changeEntity = new TUserAccountChangeEntity();
        changeEntity.setChangeId(UUID.randomUUID());
        changeEntity.setUserId(userId);
        changeEntity.setAccountTrend(accountTrendType);
        changeEntity.setBusinessId(businessId);
        changeEntity.setAccountChangeBusinessType(accountChangeBusinessType);
        //现金
        changeEntity.setCashAmount(BigDecimal.ZERO);
        changeEntity.setBeforeCashAmount(accountEntity.getCashAmount());
        changeEntity.setAfterCashAmount(accountEntity.getCashAmount());
        //金币
        changeEntity.setGoldCoinAmount(BigDecimal.ZERO);
        changeEntity.setBeforeCashAmount(accountEntity.getGoldCoinAmount());
        changeEntity.setAfterGoldCoinAmount(accountEntity.getGoldCoinAmount());
        //抽奖券
        changeEntity.setRaffleTicket(0);
        changeEntity.setBeforeRaffleTicket(accountEntity.getRaffleTicket());
        changeEntity.setAfterRaffleTicket(accountEntity.getRaffleTicket());
        changeEntity.setCreateTime(new Date());
        //佣金
        changeEntity.setBrokerageAmount(amount);
        changeEntity.setBeforeBrokerageAmount(accountEntity.getBrokerageAmount());
        switch (accountTrendType) {
            case "10000001"://收入
                changeEntity.setAfterBrokerageAmount(accountEntity.getGoldCoinAmount().add(amount));
                break;
            case "10000002"://支出
                changeEntity.setAfterGoldCoinAmount(accountEntity.getGoldCoinAmount().subtract(amount));
                amount = amount.negate();//取反，用于下面账户减去处理
                break;
            default:
                throw new RuntimeException("未知资金流向类型");
        }
        itUserAccountChangeService.insert(changeEntity);
        //账户金额减去
        TUserAccountEntity tempAccountEntity = new TUserAccountEntity();
        tempAccountEntity.setUserId(userId);
        tempAccountEntity.setBrokerageAmount(amount);
        this.updateByEntity(tempAccountEntity);
    }
}
